package com.bigtotoro.util;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;

import java.util.UUID;

/**
 * Created by Administrator on 2014/11/1.
 */
public class DeviceUtil {

    public static boolean isNetOk(Context context) {
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                // 获取网络连接管理的对象
                NetworkInfo info = connectivity.getActiveNetworkInfo();
                if (info != null && info.isConnected()) {
                    // 判断当前网络是否已经连接
                    if (info.getState() == NetworkInfo.State.CONNECTED) {
                        return true;
                    }
                }
            }
        } catch (Exception e) {
            Log.d("isNetOk", e.toString());
        }
        return false;
    }

    /**
     * 强制隐藏软键盘
     *
     * @param view
     * @param context
     */
    public static void hideKeyBoard(View view, Context context) {
        InputMethodManager imm = (InputMethodManager) context
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.showSoftInput(view, InputMethodManager.SHOW_FORCED);
        imm.hideSoftInputFromWindow(view.getWindowToken(), 0);// 强制隐藏键盘
    }
    
    /**
     * <uses-permission android:name="android.permission.READ_PHONE_STATE" /> in AndroidManifest.xml
     * @param context
     */
    public static String getPhoneNumber(Context context){  
        TelephonyManager mTelephonyMgr;  
        mTelephonyMgr = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);   
        String phone = mTelephonyMgr.getLine1Number();
        if(phone!=null && phone.startsWith("+86")){
            return phone.substring(3);
        }
        return phone;  
    }

    /**
     * 如果你想得到设备的唯一序号， TelephonyManager.getDeviceId() 就足够了。但很明显暴露了DeviceID会使一些用户不满，所以最好把这些id加密了。
     * 实际上加密后的序号仍然可以唯一的识别该设备，并且不会明显的暴露用户的特定设备，例如，使用 String.hashCode() ，结合UUID
     * @param context
     * @return
     */
    public static String getUUID(Context context){
        final TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

        final String tmDevice, tmSerial, tmPhone, androidId;
        tmDevice = "" + tm.getDeviceId();
        tmSerial = "" + tm.getSimSerialNumber();
        androidId = "" + android.provider.Settings.Secure.getString(context.getContentResolver(), android.provider.Settings.Secure.ANDROID_ID);

        UUID deviceUuid = new UUID(androidId.hashCode(), ((long)tmDevice.hashCode() << 32) | tmSerial.hashCode());
        String uniqueId = deviceUuid.toString();
        return uniqueId;
    }
}